//
//  CYCreditTool.m
//  CreditAddressBook
//
//  Created by Lee on 15/5/7.
//  Copyright (c) 2015年 Lee. All rights reserved.
//

#import "CYCreditTool.h"
#import "MJExtension.h"
#import "CYDefaultRecordAO.h"
#import "CYCommonPage.h"
#import "CYCreditCacheTool.h"
#import "CYPayBack.h"
#import "CYJsonInfo.h"
#import "CYDefaultPic.h"
#import "CYDefaultType.h"
#import "CYDefaultRecordPics.h"
#import "CYLoginHttpTool.h"
#import "LEProgressButton.h"
#import "CYNetworkCollectRecord.h"

@implementation CYCreditTool

+ (void)newsDefaultsWithParams:(NSDictionary *)params success:(void (^)(NSArray *defrs))success failure:(HttpRequestFailure)failure {
        //从网络请求中加载数据
        [CYHttpTool postWithURL:[CYURL newDefaultsPath] params:params success:^(id json) {
//            CYLog(@"json:%@", json);
            CYJsonInfo *jsonInfo = [CYJsonInfo objectWithKeyValues:json];
            if (success) {
                if (jsonInfo.isSuccess) {
                    NSArray *result = jsonInfo.data;
                    NSMutableArray *defrs = [NSMutableArray array];
                    for (NSDictionary *defr in result) {
                        CYDefaultRecordAO *de = [CYDefaultRecordAO objectWithKeyValues:defr];
                        //设置iconTag
                        de = [self setDefaultRecordAOIconTag:de];
                        [defrs addObject:de];
                    }
                    //缓存数据
                    [CYCreditCacheTool addDefaultRecords:defrs];
                    
                    //从缓存中取出数据
                    
                    success(defrs);
                } else if ([jsonInfo.message equals:@"没有更多记录"]) {
                    if (success) {
                        success(nil);
                    }
                } else {
                    if (failure) {
//                        failure(CYError(jsonInfo.message, CYErrorCodeErrorFromService));
                    }
                }
            }
        } failure:^(NSError *error) {
            if (failure) {
                failure(error);
            }
        }];
    
}

/**
 *  根据违约时间设置CYDefaultRecordAO的iconTag
 */
+ (CYDefaultRecordAO *)setDefaultRecordAOIconTag:(CYDefaultRecordAO *)de {
    //计算违约时间
    NSNumber *day = [self dayWithStartValue:[NSNumber numberWithLongLong:de.startTime.longLongValue] endValue:[NSNumber numberWithLongLong:de.endTime.longLongValue]];
//                    CYLog(@"day:%@", day);
    if (day.longValue >= 180) {
        de.iconTag = -1;
    }else if (day.longValue >= 90) {
        de.iconTag = 0;
    }else {
        de.iconTag = 1;
    }
    return de;
}

/**
 *  根据身份证号、姓名、号码等进行查询
 *
 *  @param params  身份证号、姓名、号码等
 *  @param success
 *  @param failure
 */
+ (void)defaultRecordsBySearchWithParams:(NSDictionary *)params success:(void (^)(NSArray *defrs))success failure:(HttpRequestFailure)failure {
    [CYHttpTool postWithURL:[CYURL defaultRecordsBySearchPath] params:params success:^(id json) {
//        CYLog(@"json:%@", json);
        CYJsonInfo *jsonInfo = [CYJsonInfo objectWithKeyValues:json];
        if (success) {
            if (jsonInfo.isSuccess) {
                CYCommonPage *commPage = [CYCommonPage objectWithKeyValues:jsonInfo.data];
                NSMutableArray *arr = [NSMutableArray array];
                for (CYDefaultRecordAO *dea in commPage.content) {
                    [arr addObject:[self setDefaultRecordAOIconTag:dea]];
                }
                //添加离线缓存
                [CYCreditCacheTool addDefaultRecords:arr];
                success(arr);
            }else {
                NSError *error = [NSError errorWithDomain:@"jsonFailMsg" code:-1 userInfo:@{@"message":@"没有更多数据"}];
                failure(error);
            }
        }
    } failure:^(NSError *error) {
        if (failure) {
            failure(error);
        }
    }];
    
}

/**
 *  获取总记录数
 *
 *  @param params
 *  @param success
 *  @param failure
 */
+ (void)totalCountForsuccess:(void (^)(NSNumber *total))success failure:(HttpRequestFailure)failure {
    [CYHttpTool getWithURL:[CYURL totalCountPath] params:nil success:^(id json) {
        CYJsonInfo *jsonInfo = [CYJsonInfo objectWithKeyValues:json];
        if (jsonInfo.isSuccess) {
            if (success) {
                NSDictionary *data = jsonInfo.data;
                NSNumber *total = data[@"totalCount"];
                success(total);
            } else {
                success(@(0));
            }
        }
    } failure:^(NSError *error) {
        if (failure) {
            failure(error);
        }
    }];
}

+ (void)payBacksWithParams:(NSDictionary *)params success:(void (^)(NSArray *))success failure:(HttpRequestFailure)failure {
    [CYHttpTool getWithURL:[CYURL payBacksPath] params:params success:^(id json) {
//        CYLog(@"%@", json);
//        CYLog(@"len:%@, name:%@", json[0][@"lenderPerson"], json[0][@"name"]);
        CYJsonInfo *jsonInfo = [CYJsonInfo objectWithKeyValues:json];
        if (jsonInfo.isSuccess) {
            NSArray *arr = jsonInfo.data;
            NSMutableArray *pays = [NSMutableArray array];
            for (NSDictionary *dic in arr) {
                CYPayBack *pay = [CYPayBack objectWithKeyValues:dic];
                [pays addObject:pay];
            }
            if (success) {
                success(pays);
            }
        }
    } failure:^(NSError *error) {
        if (failure) {
            failure(error);
        }
    }];
}

/**
 *  图片上传
 */
+ (void)uploadPicImage:(UIImage *)image success:(void (^)(NSString *imageUrl))success failure:(HttpRequestFailure)failure uploadProgress:(void (^)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite))block {
    [CYHttpTool postWithURL:[CYURL uploadPicPath] params:nil image:image success:^(id json) {
        //上传成功更新头像访问路径
        if ([json[@"success"] isEqualToString:@"success"]) {
            if (success) {
                success(json[@"message"]);
            }
        }else {
            if (failure) {
//                failure(CYError(json[@"message"], CYErrorCodeParamsError));
            }
        }
    } failure:^(NSError *error) {
        CYLog(@"头像上传服务器连接失败：%@", error);
        if (failure) {
            failure(error);
        }
    } uploadProgress:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
        if (block) {
            block(bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
        }
    }];
}
/**
 *  图片上传1
 */
+ (void)uploadUserImage:(UIImage *)image button:(LEProgressButton *)btn success:(void (^)(NSString *imagePath))success failure:(HttpRequestFailure1)failure {
    [btn setImage:image forState:UIControlStateNormal];
    [CYHttpTool postWithURL:[CYURL uploadPicPath] params:nil image:image success:^(id json) {
        //上传成功更新图片访问路径
        if ([json[@"success"] isEqualToString:@"success"]) {
            btn.ratio = 1;
            if (success) {
                success(json[@"message"]);
            }
        } else {
            //清除图片显示数据
             //imageuoload icon_btn_add_unpressed
            [btn setImage:[UIImage imageNamed:@"未标题-5"] forState:UIControlStateNormal];
            if (failure) {
                failure(json[@"message"], nil);
            }
        }
    } failure:^(NSError *error) {
        CYLog(@"头像上传服务器连接失败：%@", error);
        //清除图片显示数据
        [btn setImage:[UIImage imageNamed:@"未标题-5"] forState:UIControlStateNormal];
        if (failure) {
            failure(@"服务器连接失败", error);
        }
    } uploadProgress:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
        CGFloat a = totalBytesWritten;
        CGFloat b = totalBytesExpectedToWrite;
        btn.ratio = a/b - 0.01;
    }];
}

/**
 *  违约发布
 */
+ (void)saveDefaultRecordWithParams:(NSDictionary *)params success:(void (^)(NSString *message))success failure:(HttpRequestFailure)failure {
    [CYHttpTool postWithURL:[CYURL saveDefaultRecordPath] params:params success:^(id json) {
        CYJsonInfo *jsonInfo = [CYJsonInfo objectWithKeyValues:json];
        if (jsonInfo.isSuccess) {
            if (success) {
                success(jsonInfo.message);
            }
        } else if (jsonInfo.isNoLogin) {
            if (failure) {
//                failure(CYError(@"登陆信息已过期，请重新登陆", CYErrorCodeNoLogin));
            }
        } else {
            if (failure) {
//                failure(CYError(jsonInfo.message, CYErrorCodeParamsError));
            }
        }
    } failure:^(NSError *error) {
        CYLog(@"违约发布服务器链接失败：%@", error);
        if (failure) {
            failure(error);
        }
    }];
    
//    NSString *url = [CYURL saveDefaultRecordPath];
//    
//    
//    [CYHttpTool getWithURL:url params:params success:^(id json) {
//        
//    } failure:^(NSError *error) {
//        
//    }];
}

/**
 *  违约编辑
 */
+ (void)editDefaultRecordWithParams:(NSDictionary *)params success:(void (^)(CYDefaultRecord *defr))success failure:(HttpRequestFailure)failure {
    [CYHttpTool postWithURL:[CYURL editDefaultPath] params:params success:^(id json) {
//        CYLog(@"%@", json);
        @try {
            CYJsonInfo *jsonInfo = [CYJsonInfo objectWithKeyValues:json];
            if (jsonInfo.isSuccess) {
                CYDefaultRecord *record = [CYDefaultRecord objectWithKeyValues:jsonInfo.data];
                if (success) {
                    success(record);
                }
            }
        }
        @catch (NSException *exception) {
            [self.class reportException:exception reason:@"违约编辑失败"];
            CYLog(@"违约编辑json解析失败：%@", exception);
        }
    } failure:^(NSError *error) {
        
    }];
}

/**
 *  违约删除
 */
+ (void)deleteDefaultRecordWithParams:(NSDictionary *)params success:(void (^)(NSString *message))success failure:(HttpRequestFailure)failure {
    [CYHttpTool postWithURL:[CYURL delRecordPath] params:params success:^(id json) {
        CYLog(@"%@", json);
        CYJsonInfo *jsonInfo = [CYJsonInfo objectWithKeyValues:json];
        if (jsonInfo.isSuccess) {
            if (success) {
                success(jsonInfo.message);
            }
        } else {
            if (failure) {
//                failure(CYError(jsonInfo.message, CYErrorCodeParamsError));
            }
        }
    } failure:^(NSError *error) {
        
    }];
}

/**
 *  提交违约记录到审核
 */
+ (void)submitDefaultRecordWithParams:(NSDictionary *)params success:(void (^)(NSString *message))success failure:(HttpRequestFailure)failure {
    [CYHttpTool postWithURL:[CYURL submitRecordPath] params:params success:^(id json) {
        CYJsonInfo *jsonInfo = [CYJsonInfo objectWithKeyValues:json];
        if (jsonInfo.isSuccess) {
            if (success) {
                success(jsonInfo.message);
            }
        } else {
            if (failure) {
//                failure(CYError(jsonInfo.message, CYErrorCodeParamsError));
            }
        }
    } failure:^(NSError *error) {
        CYLog(@"提交违约错误：%@", error);
        if (failure) {
            failure(error);
        }
    }];
}

/**
 *  撤销违约记录
 */
+ (void)cancelDefaultRecordWithRecordId:(NSString *)recordId success:(void (^)(NSString *message))success failure:(HttpRequestFailure)failure {
    CYUser *user = [CYLoginHttpTool userData].user;
    [CYHttpTool postWithURL:[CYURL cancelRecordPath] params:@{@"id": recordId, @"userId": user.userId, @"token": user.token} success:^(id json) {
        CYJsonInfo *jsonInfo = [CYJsonInfo objectWithKeyValues:json];
        if (jsonInfo.isSuccess) {
            if (success) {
                success(jsonInfo.message);
            }
        } else {
            if (failure) {
//                failure(CYError(jsonInfo.message, CYErrorCodeParamsError));
            }
        }
    } failure:^(NSError *error) {
        CYLog(@"撤销违约错误：%@", error);
        if (failure) {
            failure(error);
        }
    }];
}

/**
 *  违约列表
 */
+ (void)entryuiWithParams:(NSDictionary *)params success:(void (^)(NSArray *defrs))success failure:(HttpRequestFailure)failure {
    [CYHttpTool postWithURL:[CYURL entryuiPath] params:params success:^(id json) {
        CYJsonInfo *jsonInfo = [CYJsonInfo objectWithKeyValues:json];
        NSArray *arr = jsonInfo.data[@"pageItems"];
        if (arr && arr.count) {
            NSArray *defrs = [CYDefaultRecord objectArrayWithKeyValuesArray:arr];
            if (success) {
                success(defrs);
            }
        } else {
            if (failure) {
//                failure(CYError(@"没有数据", CYErrorCodeNOData));
            }
        }
    } failure:^(NSError *error) {
        CYLog(@"违约列表服务器链接失败：%@", error);
        if (failure) {
            failure(error);
        }
    }];
}

/**
 *  违约图片
 *  2:图片类型（身份证正面）3:图片类型（个人信息承诺书） 4:图片类型（合同） 5:图片类型(其他) 10:图片类型（身份证反面）   14:借条，合同15:收据，凭证16:身份证（正面）17:身份证（反面）18:其他
 */
+ (void)defaultPicsWithParams:(NSDictionary *)params success:(void (^)(CYDefaultRecordPics *defrs))success failure:(HttpRequestFailure)failure {
    [CYHttpTool postWithURL:[CYURL getDefaultPicsPath] params:params success:^(id json) {
        CYLog(@"违约图片：%@", json);
        CYJsonInfo *jsonInfo = [CYJsonInfo objectWithKeyValues:json];
        if (jsonInfo.isSuccess) {
            NSArray *arr = jsonInfo.data;
            if (arr && arr.count) {
                CYDefaultRecordPics *defrPic = [[CYDefaultRecordPics alloc] init];
                NSArray *pics = [CYDefaultPic objectArrayWithKeyValuesArray:arr];
                for (CYDefaultPic *pic in pics) {
                    switch (pic.defaultType.intValue) {
                        case 2:
                              if (pic.picAddress) {
                                   [defrPic.picidCardZImageUrls addObject:pic.picAddress];

                              }
                                break;
                        case 3:
                              if (pic.picAddress) {
                                    [defrPic.picpersonImageUrls addObject:pic.picAddress];
                              }
                           
                            break;
                            
                        case 4:
                              if (pic.picAddress) {
                                   [defrPic.piccontractImageUrls addObject:pic.picAddress];

                              }
                           break;
                            
                        case 5:
                              if (pic.picAddress) {
                                   [defrPic.picotherImageUrls addObject:pic.picAddress];

                              }
                        break;
                            
                        case 10:
                              if (pic.picAddress) {
                                   [defrPic.picidCardFImageUrls addObject:pic.picAddress];

                              }
                         break;
                            
                        case 14:
                              if (pic.picAddress) {
                                   [defrPic.compactImageUrls addObject:pic.picAddress];
                              }
                            
                            break;
                            
                        case 15:
                              if (pic.picAddress) {
                                   [defrPic.certificateUrls addObject:pic.picAddress];
                              }
                            
                            break;
                            
                        case 16:
                              if (pic.picAddress) {
                                    defrPic.idCardZImageUrl = pic.picAddress;
                              }
                           
                            break;
                            
                        case 17:
                              if (pic.picAddress) {
                                   defrPic.idCardFImageUrl = pic.picAddress;
                              }
                            
                            break;
                            
                        case 18:
                              if (pic.picAddress) {
                                   [defrPic.otherImageUrls addObject:pic.picAddress];
                              }
                            
                            break;
                            
                        default:
                            break;
                    }
                    
                }
                if (success) {
                    success(defrPic);
                    CYLog(@"defrpic = %@",defrPic);
                    //
                }
            }
        } else {
            NSString *successMsg = json[@"success"];
            if (successMsg && CYStringEqualTo(@"fail", successMsg)) {
                
            } else {
                
            }
        }
    } failure:^(NSError *error) {
        CYLog(@"违约图片服务器链接失败：%@", error);
    }];
}


/**
 *  审核通过的网络收集违约人列表
 *
 *  @param param
 *  @param success
 *  @param failure
 */
+ (void)getNetworkCollectRecordsWithParam:(NSDictionary *)param success:(void (^)(NSArray *defrs))success failure:(HttpRequestFailure1)failure {
    [CYHttpTool postWithURL:[CYURL shared].getNetworkCollectRecords params:param success:^(id json) {
        CYJsonInfo *jsonInfo = [CYJsonInfo objectWithKeyValues:json];
        if (jsonInfo.isSuccess) {
            NSArray *defars = [CYNetworkCollectRecord objectArrayWithKeyValuesArray:jsonInfo.data[@"pageItems"]];
            if (success) {
                success(defars);
            }
        } else {
            if (failure) {
                failure(jsonInfo.message, nil);
            }
        }
    } failure:^(NSError *error) {
        CYLog(@"获取网络曝光错误: %@", error);
        if (failure) {
            failure(nil, error);
        }
    }];
}
/**
 *  根据身份证号、姓名、号码等进行查询网络违约人信息
 */
+ (void)getNetworkCollectRecordsBySearchWithParam:(NSDictionary *)param success:(void (^)(NSArray *defrs))success failure:(HttpRequestFailure1)failure {
    [CYHttpTool postWithURL:[CYURL shared].getNetworkCollectRecordsBySearch params:param success:^(id json) {
        CYJsonInfo *jsonInfo = [CYJsonInfo objectWithKeyValues:json];
        if (jsonInfo.isSuccess) {
            NSArray *defars = [CYNetworkCollectRecord objectArrayWithKeyValuesArray:jsonInfo.data[@"pageItems"]];
            if (success) {
                success(defars);
            }
        } else {
            if (failure) {
                failure(jsonInfo.message, nil);
            }
        }
    } failure:^(NSError *error) {
        CYLog(@"搜索网络曝光错误: %@", error);
        if (failure) {
            failure(nil, error);
        }
    }];
}

+ (void)getAuditNetworkCollectRecordNumSuccess:(void (^)(NSNumber *total))success failure:(HttpRequestFailure)failure {
    [CYHttpTool getWithURL:[CYURL shared].getAuditNetworkCollectRecordNum params:nil success:^(id json) {
        CYJsonInfo *jsonInfo = [CYJsonInfo objectWithKeyValues:json];
        if (jsonInfo.isSuccess) {
            if (success) {
                NSNumber *total = jsonInfo.data;
                success(total);
            } else {
                success(@(0));
            }
        }
    } failure:^(NSError *error) {
        if (failure) {
            failure(error);
        }
    }];
}
/**
 *  根据id查询违约人详细信息
 *
 *  @param param
 *  @param success
 *  @param failure
 */
+ (void)getAuditNetworkCollectRecordsByIdWithParam:(NSDictionary *)param success:(void (^)(CYNetworkCollectRecord *record))success failure:(HttpRequestFailure1)failure {
    [CYHttpTool postWithURL:[CYURL shared].getAuditNetworkCollectRecordsById params:param success:^(id json) {
        CYJsonInfo *jsonInfo = [CYJsonInfo objectWithKeyValues:json];
        if (jsonInfo.isSuccess) {
            NSArray *list = jsonInfo.data;
            CYNetworkCollectRecord *record = [CYNetworkCollectRecord objectWithKeyValues:list.firstObject];
            if (success) {
                success(record);
            }
        } else {
            if (failure) {
                failure(jsonInfo.message, nil);
            }
        }
    } failure:^(NSError *error) {
        CYLog(@"根据id查询违约人详细信息错误: %@", error);
        if (failure) {
            failure(nil, error);
        }
    }];
}
/**
 *  保存申述信息
 */
+ (void)saveAllegeWithParams:(NSDictionary *)params success:(void (^)(NSString *message))success failure:(HttpRequestFailure2)failure {
    [CYHttpTool postWithURL:[CYURL shared].saveAllege params:params success:^(id json) {
        CYJsonInfo *jsonInfo = [CYJsonInfo objectWithKeyValues:json];
        if (jsonInfo.isSuccess) {
            if (success) {
                success(jsonInfo.message);
            }
        } else if (jsonInfo.isNoLogin) {
            if (failure) {
                failure(nil, NO);
            }
        } else {
            if (failure) {
                failure(jsonInfo.message, YES);
            }
        }
    } failure:^(NSError *error) {
        CYLog(@"保存申述信息服务器链接失败：%@", error);
        if (failure) {
            failure(@"服务器连接失败", YES);
        }
    }];
}
/**
 *  添加网络收集违约人
 */
+ (void)addNetworkCollectRecordWithParams:(NSDictionary *)params success:(void (^)(NSString *message))success failure:(HttpRequestFailure2)failure {
    [CYHttpTool postWithURL:[CYURL shared].addNetworkCollectRecord params:params success:^(id json) {
        CYJsonInfo *jsonInfo = [CYJsonInfo objectWithKeyValues:json];
        if (jsonInfo.isSuccess) {
            if (success) {
                success(jsonInfo.message);
            }
        } else if (jsonInfo.isNoLogin) {
            if (failure) {
                failure(nil, NO);
            }
        } else {
            if (failure) {
                failure(jsonInfo.message, YES);
            }
        }
    } failure:^(NSError *error) {
        CYLog(@"添加网络收集违约人服务器链接失败：%@", error);
        if (failure) {
            failure(@"服务器连接失败", YES);
        }
    }];
}

#pragma mark -
/**
 *  将date转换为format格式的字符串时间
 *
 *  @param date
 *
 *  @return 时间
 */
+ (NSString *)timeWithDate:(NSDate *)date formatter:(NSString *)format{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:format];
    dateFormatter.timeZone = [NSTimeZone localTimeZone];//设置时区
    NSString *time = [dateFormatter stringFromDate:date];
    return time;
}

/**
 *  将format格式的字符串转换为date
 *
 *  @param date
 *
 *  @return 时间
 */
+ (NSDate *)dateWithDateStr:(NSString *)dateStr formatter:(NSString *)format {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:format];
    dateFormatter.timeZone = [NSTimeZone localTimeZone];//设置时区
    NSDate *date = [dateFormatter dateFromString:dateStr];
    return date;
}
/**
 *  将服务器返回的date时间转为yyyy年MM月dd日格式的字符串时间
 *
 *  @param value JavaDate
 *
 *  @return 时间
 */
+ (NSString *)timewithLongLongValue:(long long)value formatter:(NSString *)formatter {
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:value/1000];//Java的date/1000就是oc的NSDate
    if (!formatter || formatter.isEmpty) {
        formatter = CYDefaultTimeFormatType;
    }
    return [self timeWithDate:date formatter:formatter];
}

/**
 *  根据服务器返回的date时间计算天数差
 *
 *  @param start 起始时间 end 结束时间
 *
 *  @return 天数
 */
+ (NSNumber *)dayWithStartValue:(NSNumber *)start endValue:(NSNumber *)end{
    if (end && end.longLongValue != 0) {
        long long value = end.longLongValue - start.longLongValue;
        long long day = value/1000/(24 * 3600);
        return [NSNumber numberWithLongLong:day];
    }
    NSString *startTime = [self timewithLongLongValue:start.longLongValue formatter:nil];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:CYDefaultTimeFormatType];
    NSDate *startDate = [dateFormatter dateFromString:startTime];
    long day = startDate.timeIntervalSinceNow/(24*3600);
    
//    NSDate *now = [NSDate date];
//    NSString *nowTime = [self timeWithDate:now formatter:CYTimeFormatYMDHmSType];
////    NSDate *nowDate = [nowTime da ];
//    
//    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//    [dateFormatter setDateFormat:CYTimeFormatYMDHmSType];
//    dateFormatter.timeZone = [NSTimeZone localTimeZone];//设置时区
//    NSDate *date1 = [dateFormatter dateFromString:nowTime];
//    int r = date1.timeIntervalSince1970;
//    int e = date1.timeIntervalSinceNow;
//    NSDate *date = [dateFormatter dateFromString:[dateFormatter stringFromDate:now]];// 时分秒转为00:00:00
//    NSTimeInterval time = [now timeIntervalSinceDate:date];
//    CYLog(@"%f", time/(24*3600));
//    NSTimeInterval d = [NSDate timeIntervalSinceReferenceDate];
//    NSInteger a = d - start.longLongValue/1000;
//    NSInteger value = time - start.longLongValue/1000;
//    NSInteger day = value/(24 * 3600);
    return [NSNumber numberWithInteger:-day];
}

/**
 *  根据经纬度获取城市信息
 *
 *  @param param ak，callback，location，output=json，pois=1
 *  @param success
 *  @param failure
 */
+ (void)areaWithParam:(NSDictionary *)param success:(void (^)(NSDictionary *cityInfo))success failure:(HttpRequestFailure)failure {
    NSDictionary *params = @{@"ak": ak, @"callback": @"renderReverse", @"location": [NSString stringWithFormat:@"%@,%@", param[@"lat"], param[@"lng"]], @"output": @"json", @"pois": @"1"};
    [CYHttpTool postWithURL:CYUNGEOCODINGPATH params:params success:^(id json) {
        NSDictionary *result = json[@"result"];
        NSDictionary *addressComponent = result[@"addressComponent"];
        if (success) {
            success(@{@"province": addressComponent[@"province"], @"city": addressComponent[@"city"]});
        }
    } failure:^(NSError *error) {
        if (failure) {
            failure(error);
        }
    }];
}

+ (NSDictionary *)idCardInfo:(NSString *)idCard {
    if (idCard.length == 18) {
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        NSString *yy = [idCard substringFromIndex:6 toIndex:10];//出生的年份
        NSString *sex = [idCard substringFromIndex:16 toIndex:17];//
        if (![sex equals:@"*"]) {
            int sexInt = sex.intValue;
            if (sexInt%2 != 0) {
                sex = @"男";
            } else {
                sex = @"女";
            }
        } else {
            sex = @"--";
        }
        dic[@"sex"] = sex;
        
//        NSString *reg = @"^(19|20)\\d{2}(1[0-2]|0?[1-9])(0?[1-9]|[1-2][0-9]|3[0-1])$";
        NSString *reg = @"^(19|20)\\d{2}$";
        NSRange range = [yy rangeOfString:reg options:NSRegularExpressionSearch];
        long long age = 0;
        if (range.length > 0) {
            NSDate *birthday = [self dateWithDateStr:yy formatter:CYTimeFormatYType];
            NSTimeInterval ageDate = [NSDate date].timeIntervalSince1970 - birthday.timeIntervalSince1970;
            age = ageDate/(24 * 3600 * 365);
            dic[@"age"] = @(age);
            dic[@"birthday"] = yy;
        } else {
            dic[@"age"] = @"--";
            dic[@"birthday"] = @"--";
        }
//        CYLog(@"borthday:%@---sex:%@---age:%lld", yy, sex, age);
        return dic;
    }
    return @{@"age": @"--", @"sex": @"--"};
}
@end
